import utils from "../../utils/index";
import {
  fansModel,
  commonModel
} from "../../apis/index"
import {
  InterAd
} from '../../utils/InterAd'
import regeneratorRuntime from '../../libs/wxPromise.min';
Page({

  data: {
    fid: '',
    list: [{
      name: '集结'
    }, {
      name: '规则说明'
    }, {
      name: '发起历史'
    }],
    timeStr: ['00', '00', '00'],
    tabIndex: 0,
    rules: [], // 集结规则
    history: [] // 集结发起历史
  },
  mixins: [require('../../myMixin.js')],
  async onLoad(options) {
    /**
     * 查看集结是否已经结束
     * 查看是否属于自己
     */
    let {
      fid = '', type = '', sid = ''
    } = options


    if (!fid) {
      utils.navigateBack({
        delta: 1
      })
      return
    }
    this.data.type = type
    this.data.fid = fid
    this.data.sid = sid
    
  },
  onReady: function () {
    let interAd = new InterAd('7fb828e435af61d59234ae3978c20221')
    interAd.showAd()
  },
  async onShow () {
    let {fid,sid,type} = this.data
    let data = {
      fid: fid
    }
    let fansClubInfo = await fansModel.fansClubInfo({
      fid
    })
    data.info = fansClubInfo

    this.setData(data)
    if (type && type == 2 && sid) { //签到
      if (fansClubInfo.type == '0') {
        utils.showToast('请先加入该再签到', 'none')
      } else if (fansClubInfo.type == '1') {
        utils.goUrl(`../signIn/index?fid=${fid}&&sid=${sid}`)
      }
    }
    if (type && type == 1 && fansClubInfo.type != 2) { //加入集结
      this.showModal()
    }
    this.getShareInfo({
      type: 2,
      sid: fansClubInfo.sid
    })
    // 清除type值,避免显示的时候再
    this.data.type = ''
  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  massAdd() {
    let {
      mid
    } = this.data.info.miss
    fansModel.massAdd({
      mid
    }).then(res => {
      utils.showToast('成功加入集结', 'none')
      fansModel.queryMissInfo({
        mid
      }).then(res => {
        clearInterval(this.countTimer)
        this.countTime(res.time, () => {
          fansModel.queryMissInfo({
            mid
          }).then(res => {
            this.setData({
              missInfo: res
            })
          })
        })
        this.setData({
          missInfo: res
        })
      })
    })
  },
  onShareAppMessage: function () {
    let {
      text,
      image
    } = this.data.share_data
    return {
      title: text,
      path: `pages/club/index?fid=${this.data.fid}&&type=1`,
      imageUrl: image
    }
  },
  getFansClubInfo() {
    let {
      fid
    } = this.data
    fansModel.fansClubInfo({
      fid
    }).then(res => {
      this.setData({
        info: res
      })
    })
  },
  async addFanClub() {
    let {
      fid,
      info
    } = this.data
    let confirm = await utils.showModalContent(`确定加入 ${info.name}?`, `所属名星: ${info.sname}`, '确定', true, '取消')

    if (confirm) {
      fansModel.addFansClub({
        fid
      }).then(res => {
        utils.showToast('成功加入该粉丝团', 'none')
        this.getFansClubInfo(fid)
      })
    }
  },
  changeBackground() {
    let {
      info
    } = this.data

    if (info.level == 1 || info.level == 2) { //团才和管理员可以修改背景图
      let _this = this
      utils.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (result) => {
          let filePath = result.tempFilePaths[0]
          commonModel.uploadFile({
            filePath
          }).then(res => {
            let param = {
              fid: info.id,
              background: res
            }
            fansModel.changeBgImage(param).then(rt => {
              _this.setData({
                [`info.background`]: res
              })
            })

          })
        }
      })
    }
  },
  goUrl(e) {
    let url = e.currentTarget.dataset.url
    utils.goUrl(url)
  },
  goSign(e) {
    let {
      info
    } = this.data
    if (info.type == 0) {
      utils.showToast('请先加入粉丝团', 'none')
      return
    }
    let url = e.currentTarget.dataset.url
    utils.goUrl(url)
  },
  countTime(time, callBack) {
    this.countTimer = setInterval(() => {
      let obj = utils.countTime(time)
      let {
        isOver,
        days,
        hours,
        minutes,
        seconds
      } = obj
      let str = ""
      if (!isOver) {
        str = [`${utils.formatNumber(hours)}`, `${utils.formatNumber(minutes)}`, `${utils.formatNumber(seconds)}`]
      } else {
        clearInterval(this.countTimer)
        this.countTimer = null
        callBack && callBack()
      }
      this.setData({
        timeStr: str
      })
    }, 1000)

  },
  tabClick(e) {
    let index = e.detail.index

    this.setData({
      tabIndex: index
    }, () => {
      if (index == 1) {
        this.massRule()
      } else if (index == 2) {
        this.massHistory()
      }
    })
  },
  async massRule() {
    let {
      rules
    } = this.data
    if (!rules.length) {
      rules = await fansModel.massRule()
    }
    this.setData({
      rules
    })
  },
  async massHistory() {
    let {
      fid
    } = this.data
    let history = await fansModel.massHistory({
      fid
    })

    this.setData({
      history
    })
  },
  hideModal() {
    this.setData({
      modalName: ''
    })
  },
  async showModal(e) {
    let {
      miss
    } = this.data.info
    if (miss.mid && miss.type != 2) { // 在集结中的话要查询集结信息
      let mid = miss.mid
      utils.showLoading()
      let missInfo = await fansModel.queryMissInfo({
        mid
      })
      clearInterval(this.countTimer)
      this.countTime(missInfo.time, () => {
        fansModel.queryMissInfo({
          mid
        }).then(res => {
          this.setData({
            missInfo: res
          })
        })

      })
      this.setData({
        missInfo: missInfo,
        modalName: 'listModal'
      }, () => {
        utils.hideAll()
      })
    } else {
      this.setData({
        modalName: 'listModal'
      })
    }

  },
  async aggregation() {
    let fid = this.data.fid
    let {
      mid
    } = await fansModel.aggregation({
      fid
    })
    let missInfo = await fansModel.queryMissInfo({
      mid
    })
    this.setData({
      ['info.miss']: {
        type: 0,
        mid: mid
      },
      missInfo: missInfo
    }, () => {
      this.countTime(missInfo.time, this.getFansClubInfo)
    })

  },
  async signOut() {
    let {
      fid,
      info
    } = this.data
    let tip = '确定退出该粉丝团?'
    if (info.level == 1) {
      tip = '确定解散该团?'
    }
    let show = await utils.showModalContent("提示", tip, '同意', true, '取消')
    if (show) {
      let res = await fansModel.signOut({
        fid
      })
      if (res) {
        utils.showToast('退出成功', 'none')
        if (info.level == 1) {
          utils.prefix.navigateBack({
            delta: 1
          })
        }
        let fansClubInfo = await fansModel.fansClubInfo({
          fid
        })
        this.setData({
          info: fansClubInfo
        })
      }
    }
  },
  toIndex() {
    utils.reLaunch({
      url: '../rank/index?tabIndex=0'
    })
  },
  showActionSheet() {
    let {
      info,
      fid
    } = this.data
    if (info.level == 1) {
      utils.prefix.showActionSheet({
        itemList: ['修改背景', '编辑资料'],
        itemColor: '#000000',
        success: (res) => {
          let index = res.tapIndex
          switch (index) {
            case 0:
              this.changeBackground()
              break;
            case 1:
              utils.goUrl(`../editClub/index?fid=${fid}`)
              break;
          }
        },
        fail: () => {},
        complete: () => {}
      });
    }

  }
})